package initialize

import (
	"fmt"
	"github.com/hashicorp/consul/api"
	_ "github.com/mbobakov/grpc-consul-resolver" // It's important
	"github.com/opentracing/opentracing-go"
	"go.uber.org/zap"
	"google.golang.org/grpc"
	"mxshop-api/goods-web/global"
	"mxshop-api/goods-web/proto"
	"mxshop-api/goods-web/utils/otgrpc"
)

// 2 负载均衡的形式初始化grpc连接
func InitSrvConnLb() {
	consulInfo := global.ServerConfig.ConsulInfo
	userConn, err := grpc.Dial(
		fmt.Sprintf("consul://%s:%d/%s?wait=14s", consulInfo.Host, consulInfo.Port, global.ServerConfig.GoodsSrvInfo.Name),
		grpc.WithInsecure(),
		grpc.WithDefaultServiceConfig(`{"loadBalancingPolicy": "round_robin"}`),
		//添加链路追踪的拦截器
		grpc.WithUnaryInterceptor(otgrpc.OpenTracingClientInterceptor(opentracing.GlobalTracer())),
	)
	if err != nil {
		zap.S().Fatal("[InitSrvConn] 连接 【商品服务失败】")
	}

	goodsSrvClient := proto.NewGoodsClient(userConn)
	global.GoodsSrvClient = goodsSrvClient

}

// 1 直接获取grpc的连接
func InitSrvConn() {

	//userSrvIp := global.ServerConfig.UserSrvInfo.Host
	//userSrvPort := global.ServerConfig.UserSrvInfo.Port

	cfg := api.DefaultConfig()
	consulInfo := global.ServerConfig.ConsulInfo
	cfg.Address = fmt.Sprintf("%s:%d", consulInfo.Host, consulInfo.Port)
	goodsSrvIp := ""
	goodsSrvPort := 0
	client, err := api.NewClient(cfg)
	if err != nil {
		panic(err)
	}
	data, err := client.Agent().ServicesWithFilter(fmt.Sprintf(`Service == "%s"`, global.ServerConfig.GoodsSrvInfo.Name))
	if err != nil {
		panic(err)
	}
	for _, service := range data {
		goodsSrvIp = service.Address
		goodsSrvPort = service.Port
		break
	}
	if goodsSrvIp == "" {
		zap.S().Fatalf("[InitSrvConn] 连接goods-srv grpc服务失败")
	}

	//拨号连接用户grpc服务器
	goodsConn, err := grpc.Dial(fmt.Sprintf("%s:%d", goodsSrvIp, goodsSrvPort), grpc.WithInsecure())
	if err != nil {
		zap.S().Errorw("[GetUserList连接]商品服务失败", "msg", err.Error())
	}

	//设置全局的关于GRPC的userClient
	global.GoodsSrvClient = proto.NewGoodsClient(goodsConn)

}
